# -*- coding: utf-8 -*-
from django.shortcuts import render, redirect
from django.http.response import JsonResponse
from django import forms
from django.views import View
from crm import models
from utils.pagination import Pagination


class DepartForm(forms.ModelForm):
	def __init__(self, *args, **kwargs):
		super().__init__(*args, **kwargs)
		for field in self.fields.values():
			field.widget.attrs = {'class': 'form-control'}
			
		self.fields['name'].error_messages = {
			'required': '必填项'
		}

	class Meta:
		model = models.Department
		fields = '__all__'


class Department_list(View):
	'''部门列表'''
	def get(self, request):
		depart_all = models.Department.objects.all()
		page_obj = Pagination(len(depart_all), request.GET.get('page'))
		page_html = page_obj.page_html
		depart_list = depart_all[page_obj.start:page_obj.end]
		return render(request, 'department_list.html', locals())


class Department_add(View):
	'''添加部门'''
	def get(self, request):
		depart_form = DepartForm()
		return render(request, 'department_add.html', locals())

	def post(self, request):
		depart_form = DepartForm(request.POST)
		if depart_form.is_valid():
			depart_form.save()
			return redirect('department_list')
		return render(request, 'department_add.html', locals())


class Department_edit(View):
	'''编辑部门'''
	def get(self, request, pk):
		depart_obj = models.Department.objects.filter(pk=pk).first()
		depart_form = DepartForm(instance=depart_obj)
		return render(request, 'department_edit.html', locals())

	def post(self, request, pk):
		depart_obj = models.Department.objects.filter(pk=pk).first()
		depart_form = DepartForm(request.POST, instance=depart_obj)
		if depart_form.is_valid():
			depart_form.save()
			return redirect('department_list')
		return render(request, 'department_edit.html', locals())


class Department_del(View):
	'''删除部门'''
	def post(self, request, pk):
		ret = {'status': 0, 'msg': '删除成功'}
		if not models.Department.objects.filter(pk=pk).delete():
			ret['msg'] = '删除失败'
		return JsonResponse(ret)